//初始化
var dev_hight = device.height;
var dev_width = device.width;
if (dev_hight && dev_width == 0) { toastLog('BUG啦，请重启手机'); exit(); }
console.show();

//子线程 音量键关闭
threads.start(function () {
    events.observeKey();
    events.onKeyDown("volume_up", function (event) { toastLog("\n音量+被按下，即将结束脚本！"); sleep(3000); console.hide(); exit(); });
});

// 特殊任务列表：
specialTasks_15 = ["15秒", , "逛大型超市"]
tasks_0 = ['浏览', "抽手机", "花呗翻翻卡", "逛借钱", "逛一逛", "支小镇", "话费券","吃货红包"]

//检测并点击
function check_click() {
    text('下单任务').waitFor();
    sleep(2000);
    outer:
    while (1) {
        gotoAPP();
        sleep(2000);
        let list_15sec = []
        let list_0sec = []

        for (let index = 0; index < specialTasks_15.length; index++) {
            let taskName = specialTasks_15[index];
            let tempList = textContains(taskName).find();
            if (tempList.length > 0) {
                list_15sec = list_15sec.concat(tempList);
                log("15sec-taskName:" + taskName);
            }

        }
        for (let index = 0; index < tasks_0.length; index++) {
            let taskName = tasks_0[index];
            let tempList = textContains(taskName).find();
            if (tempList.length > 0) {
                list_0sec = list_0sec.concat(tempList);
                log("0sec-taskName:" + taskName)
            }

        }

        for (i = 0; i < list_15sec.length; i++) {
            if (list_15sec[i] && list_15sec[i].parent().child(2).text() != '奖励已到账') {
                sleep(1000);
                list_15sec[i].parent().child(2).click();
                console.log(list_15sec[i].parent().child(0).getText())
                console.log('等待...');
                textMatches("任务完成|点击返回").findOne(25000);
                back(); sleep(500);
                if (text('晚点再来').findOne(2000)) text('晚点再来').click();
                sleep(1000);
                text('逛逛任务').waitFor();
                sleep(1000);
                continue outer;
            }
        }

        for (i = 0; i < list_0sec.length; i++) {
            if (list_0sec[i] && list_0sec[i].parent().child(2).text() != '奖励已到账') {
                list_0sec[i].parent().child(2).click();
                sleep(3000);
                back();
                if (text('晚点再来').findOne(2000)) text('晚点再来').click();
                sleep(1000);
                text('逛逛任务').waitFor();
                sleep(1000);
                continue outer;
            }
        }
        break;
    }
    toastLog('任务1 基本完成');
}

function gotoAPP() {
    app.startActivity({
        packageName: "me.ele",
        data: 'eleme://web?&url=https://h5.ele.me/svip/task-list'
    });
}
//启动并跳转
toastLog('启动饿了么\n按下音量+ 脚本停止');
home(); sleep(2000);

gotoAPP();
//主程序
check_click();
exit();